import request from '@/utils/request'
import { API_CONFIG, getApiUrl } from '@/config'
import type { ApiResponse, PageQuery, PageResponse } from '@/types'

/**
 * 基础 API 服务类
 * 提供通用的 CRUD 操作方法
 */
export class BaseApiService<T = any> {
  protected endpoint: string

  constructor(endpoint: string) {
    this.endpoint = endpoint
  }

  /**
   * 获取列表数据
   */
  async getList(params?: PageQuery & Record<string, any>): Promise<ApiResponse<PageResponse<T>>> {
    return request.get<PageResponse<T>>(this.endpoint, params)
  }

  /**
   * 获取详情数据
   */
  async getDetail(id: number | string): Promise<ApiResponse<T>> {
    return request.get<T>(`${this.endpoint}/${id}`)
  }

  /**
   * 创建数据
   */
  async create(data: Partial<T>): Promise<ApiResponse<T>> {
    return request.post<T>(this.endpoint, data)
  }

  /**
   * 更新数据
   */
  async update(id: number | string, data: Partial<T>): Promise<ApiResponse<T>> {
    return request.put<T>(`${this.endpoint}/${id}`, data)
  }

  /**
   * 删除数据
   */
  async delete(id: number | string): Promise<ApiResponse<void>> {
    return request.delete(`${this.endpoint}/${id}`)
  }

  /**
   * 批量删除
   */
  async batchDelete(ids: (number | string)[]): Promise<ApiResponse<void>> {
    return request.post(`${this.endpoint}/batch-delete`, { ids })
  }
}

/**
 * API 工具类
 * 提供便捷的API调用方法
 */
export class ApiService {
  /**
   * 构建查询参数
   */
  static buildQuery(params: Record<string, any>): string {
    const queryParams = new URLSearchParams()
    
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        if (Array.isArray(value)) {
          value.forEach(item => queryParams.append(key, String(item)))
        } else {
          queryParams.append(key, String(value))
        }
      }
    })
    
    return queryParams.toString()
  }

  /**
   * 构建完整的API URL
   */
  static buildUrl(endpoint: string, params?: Record<string, any>): string {
    const baseUrl = getApiUrl(endpoint)
    if (params) {
      const query = this.buildQuery(params)
      return query ? `${baseUrl}?${query}` : baseUrl
    }
    return baseUrl
  }

  /**
   * 处理API响应
   */
  static handleResponse<T>(response: ApiResponse<T>): T {
    if (response.success || response.code === 200) {
      return response.data
    }
    throw new Error(response.msg || '请求失败')
  }

  /**
   * 安全的API调用
   */
  static async safeCall<T>(
    apiCall: () => Promise<ApiResponse<T>>,
    fallback?: T
  ): Promise<T> {
    try {
      const response = await apiCall()
      return this.handleResponse(response)
    } catch (error) {
      console.error('API调用失败:', error)
      if (fallback !== undefined) {
        return fallback
      }
      throw error
    }
  }

  /**
   * 重试机制的API调用
   */
  static async retryCall<T>(
    apiCall: () => Promise<ApiResponse<T>>,
    retryCount: number = API_CONFIG.REQUEST_CONFIG.RETRY_COUNT,
    delay: number = API_CONFIG.REQUEST_CONFIG.RETRY_DELAY
  ): Promise<ApiResponse<T>> {
    let lastError: Error
    
    for (let i = 0; i <= retryCount; i++) {
      try {
        return await apiCall()
      } catch (error) {
        lastError = error as Error
        
        if (i < retryCount) {
          await new Promise(resolve => setTimeout(resolve, delay * (i + 1)))
        }
      }
    }
    
    throw lastError!
  }

  /**
   * 并发API调用
   */
  static async parallel<T extends Record<string, () => Promise<any>>>(
    apiCalls: T
  ): Promise<{ [K in keyof T]: Awaited<ReturnType<T[K]>> }> {
    const keys = Object.keys(apiCalls) as (keyof T)[]
    const promises = keys.map(key => apiCalls[key]())
    
    const results = await Promise.all(promises)
    
    return keys.reduce((acc, key, index) => {
      acc[key] = results[index]
      return acc
    }, {} as any)
  }
}

export default ApiService